<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { addGoods, getGoodsInfo, editGoods, getGoodsCategoryList } from '@/api/goods'
import { uploadFile } from '@/api/upload'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { formatTime } from '@/utils/index'

const router = useRouter()
const route = useRoute()

// 优先用props（路由配置可传props），否则用query
const mode = computed(() => route.query.mode || route.params.mode || 'add')
const id = computed(() => {
  const raw = route.query.id || route.params.id
  if (Array.isArray(raw)) return Number(raw[0])
  return raw ? Number(raw) : undefined
})
const isView = computed(() => mode.value === 'view')
const isEdit = computed(() => mode.value === 'edit')
const isAdd = computed(() => mode.value === 'add')

// 图片预览相关
const imagePreviewVisible = ref(false)
const imagePreviewUrl = ref('')

// 图片预览方法
const handleImagePreview = (url: string | File) => {
  // 清理之前的 blob URL
  if (imagePreviewUrl.value && imagePreviewUrl.value.startsWith('blob:')) {
    URL.revokeObjectURL(imagePreviewUrl.value)
  }

  if (url instanceof File) {
    // 如果是 File 对象，创建本地 URL
    imagePreviewUrl.value = URL.createObjectURL(url)
  } else {
    // 如果是字符串 URL，添加/api/前缀
    const fullUrl = url.startsWith('/api/') ? url : `/api/${url}`
    imagePreviewUrl.value = fullUrl
  }
  imagePreviewVisible.value = true
}

// 处理上传组件的预览事件
const handleUploadPreview = (file: any) => {
  if (file.raw) {
    // 如果是新上传的文件
    handleImagePreview(file.raw)
  } else if (file.url) {
    // 如果是已有的文件
    handleImagePreview(file.url.replace('/api/', ''))
  } else {
    // 如果是文件名
    handleImagePreview(file.name)
  }
}

// 关闭预览弹窗
const closeImagePreview = () => {
  // 清理 blob URL
  if (imagePreviewUrl.value && imagePreviewUrl.value.startsWith('blob:')) {
    URL.revokeObjectURL(imagePreviewUrl.value)
  }
  imagePreviewVisible.value = false
  imagePreviewUrl.value = ''
}

const form = ref({
  code: '',
  category_id: null,
  category_name: '',
  name: '',
  sub_name: '',
  status: 1,
  sort: 0,
  show_position: null,
  price: 0, // 商品价格
  main_img: '',
  goods_img: [], // 商品图片数组
  goods_info: [], // 商品详情图片数组
  goods_service: '', // 商品服务图片
  reason: '',
  id: null,
  created_at: '',
})

// 用于存储编辑时的原始图片URL（用于区分新旧图片）
const originalGoodsImg = ref([])
const originalGoodsInfo = ref([])

// 用于上传组件的文件列表
const mainImgFileList = ref([])
const goodsImgFileList = ref([])
const goodsInfoFileList = ref([])
const goodsServiceFileList = ref([])

// 上传相关
const mainImgUploadRef = ref()
const goodsImgUploadRef = ref()
const goodsInfoUploadRef = ref()
const goodsServiceUploadRef = ref()
const imageUrl = ref('')
const goodsImages = ref([])
const uploadLoading = ref(false)

const handleMainImgChange = (file) => {
  if (file.raw) {
    // 验证文件大小 (2MB = 2 * 1024 * 1024 bytes)
    const maxSize = 2 * 1024 * 1024
    if (file.raw.size > maxSize) {
      ElMessage.error('图片大小不能超过 2MB')

      // 移除文件
      if (mainImgUploadRef.value) {
        mainImgUploadRef.value.clearFiles()
        form.value.main_img = ''
        mainImgFileList.value = []
      }
      return
    }
    form.value.main_img = file.raw
  }
}

const handleGoodsServiceChange = (file) => {
  console.log('商品服务图片上传:', file)
  if (file.raw) {
    // 验证文件大小 (2MB = 2 * 1024 * 1024 bytes)
    const maxSize = 2 * 1024 * 1024
    if (file.raw.size > maxSize) {
      ElMessage.error('图片大小不能超过 2MB')

      // 移除文件
      if (goodsServiceUploadRef.value) {
        goodsServiceUploadRef.value.clearFiles()
        form.value.goods_service = ''
        goodsServiceFileList.value = []
      }
      return
    }

    form.value.goods_service = file.raw
  }
}

const handleGoodsImgChange = (file) => {
  console.log(file, 'file')
  if (file.raw) {
    // 验证文件大小 (2MB = 2 * 1024 * 1024 bytes)
    const maxSize = 2 * 1024 * 1024
    if (file.raw.size > maxSize) {
      ElMessage.error('图片大小不能超过 2MB')

      // 移除文件
      if (goodsImgUploadRef.value) {
        goodsImgUploadRef.value.clearFiles()
        form.value.goods_img = []
        goodsImgFileList.value = []
      }
      return
    }
    // 将新文件添加到数组中
    form.value.goods_img.push(file.raw)
  }
}

const handleGoodsInfoChange = (file) => {
  if (file.raw) {
    // 验证文件大小 (2MB = 2 * 1024 * 1024 bytes)
    const maxSize = 2 * 1024 * 1024
    if (file.raw.size > maxSize) {
      ElMessage.error('图片大小不能超过 2MB')

      // 移除文件
      if (goodsInfoUploadRef.value) {
        goodsInfoUploadRef.value.clearFiles()
        form.value.goods_info = []
        goodsInfoFileList.value = []
      }
      return
    }
    // 将新文件添加到数组中
    form.value.goods_info.push(file.raw)
  }
}

// 删除商品图片
const handleGoodsImgRemove = (file) => {
  console.log('删除商品图片:', file)

  // 从 form 中移除
  const index = form.value.goods_img.findIndex((item) => {
    if (typeof item === 'string') {
      // 如果是URL，需要去掉/api/前缀来匹配
      const itemUrl = item.startsWith('/api/') ? item.replace('/api/', '') : item
      const fileUrl = file.url ? file.url.replace('/api/', '') : file.name
      return itemUrl === fileUrl
    }
    return item === file.raw
  })

  if (index > -1) {
    form.value.goods_img.splice(index, 1)
    console.log('从form中删除商品图片，剩余:', form.value.goods_img)
  }
}

// 删除商品详情图片
const handleGoodsInfoRemove = (file) => {
  console.log('删除商品详情图片:', file)

  // 从 form 中移除
  const index = form.value.goods_info.findIndex((item) => {
    if (typeof item === 'string') {
      // 如果是URL，需要去掉/api/前缀来匹配
      const itemUrl = item.startsWith('/api/') ? item.replace('/api/', '') : item
      const fileUrl = file.url ? file.url.replace('/api/', '') : file.name
      return itemUrl === fileUrl
    }
    return item === file.raw
  })

  if (index > -1) {
    form.value.goods_info.splice(index, 1)
    console.log('从form中删除商品详情图片，剩余:', form.value.goods_info)
  }
}

// 删除商品主图
const handleMainImgRemove = (file) => {
  console.log('删除商品主图:', file)
  form.value.main_img = ''
  console.log('主图已清空')
}

// 删除商品服务图片
const handleGoodsServiceRemove = (file) => {
  console.log('删除商品服务图片:', file)
  form.value.goods_service = ''
  console.log('商品服务图片已清空')
}

// 表单校验规则
const rules = {
  code: [{ required: true, message: '请输入商品编号', trigger: 'blur' }],
  category_id: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { max: 10, message: '商品名称最多10个字符', trigger: 'blur' },
  ],
  sub_name: [
    { required: true, message: '请输入商品副标题', trigger: 'blur' },
    { max: 30, message: '商品副标题最多30个字符', trigger: 'blur' },
  ],
  status: [{ required: true, message: '请选择商品状态', trigger: 'change' }],
  sort: [{ required: true, message: '请输入商品权重', trigger: 'blur' }],
  show_position: [{ required: true, message: '请选择展示区域', trigger: 'change' }],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    {
      pattern: /^\d+(\.\d{1,2})?$/,
      message: '请输入正确的价格格式（最多两位小数）',
      trigger: 'blur',
    },
  ],
  main_img: [{ required: true, message: '请上传商品主图', trigger: 'change' }],
  goods_img: [{ required: true, message: '请上传商品图片', trigger: 'change' }],
  goods_info: [{ required: true, message: '请输入商品详情', trigger: 'blur' }],
  goods_service: [{ required: true, message: '请上传商品服务图片', trigger: 'change' }],
  reason: [{ required: true, message: '请输入说明', trigger: 'blur' }],
}

const formRef = ref()

const goodsCategoryList = ref([])

const getGoodsCategoryAPi = async () => {
  const res = await getGoodsCategoryList()
  goodsCategoryList.value = res.data || []
}

const loadDetail = async () => {
  getGoodsCategoryAPi()
  if (!id.value || isAdd.value) return
  try {
    const res = await getGoodsInfo(id.value)
    const data = res.data || {}

    // 基础字段
    form.value.code = data.code || ''
    form.value.name = data.name || ''
    form.value.sub_name = data.sub_name || ''
    form.value.reason = data.reason || ''
    form.value.id = data.id || ''
    // 数字字段处理
    form.value.category_id =
      Number(Array.isArray(data.category_id) ? data.category_id[0] : data.category_id) || 0
    form.value.status = Number(Array.isArray(data.status) ? data.status[0] : data.status) || 1
    form.value.sort = Number(Array.isArray(data.sort) ? data.sort[0] : data.sort) || 0
    form.value.show_position =
      Number(Array.isArray(data.show_position) ? data.show_position[0] : data.show_position) || 0
    form.value.price = Number(Array.isArray(data.price) ? data.price[0] : data.price) || 0
    form.value.category_name = data.category_name || ''
    form.value.created_at = data.created_at || ''
    // 处理商品主图
    if (data.main_img) {
      form.value.main_img = data.main_img
      mainImgFileList.value = [
        {
          name: 'main_img.png',
          url: `/api/${data.main_img}`,
          status: 'success',
        },
      ]
    }

    // 处理商品图片
    if (data.goods_img && Array.isArray(data.goods_img)) {
      form.value.goods_img = data.goods_img
      originalGoodsImg.value = [...data.goods_img]

      goodsImgFileList.value = data.goods_img.map((url, index) => ({
        name: `goods_img_${index}.png`,
        url: `/api/${url}`,
        status: 'success',
      }))
    }

    // 处理商品详情图片
    if (data.goods_info && Array.isArray(data.goods_info)) {
      form.value.goods_info = data.goods_info
      originalGoodsInfo.value = [...data.goods_info]

      goodsInfoFileList.value = data.goods_info.map((url, index) => ({
        name: `goods_info_${index}.png`,
        url: `/api/${url}`,
        status: 'success',
      }))
    }

    // 处理商品服务图片
    if (data.goods_service) {
      form.value.goods_service = data.goods_service
      goodsServiceFileList.value = [
        {
          name: 'goods_service.png',
          url: `/api/${data.goods_service}`,
          status: 'success',
        },
      ]
    }
  } catch (error) {
    console.error('加载商品详情失败:', error)
    ElMessage.error('加载商品详情失败')
  }
}
onMounted(loadDetail)

// 组件卸载时清理 URL 对象
onUnmounted(() => {
  if (imagePreviewUrl.value && imagePreviewUrl.value.startsWith('blob:')) {
    URL.revokeObjectURL(imagePreviewUrl.value)
  }
})

const onSubmit = async () => {
  // 表单验证
  await formRef.value.validate()

  // 创建 FormData 对象
  const formData = new FormData()
  form.value.sort = Number(form.value.sort)
  // 添加普通字段
  formData.append('code', form.value.code)
  formData.append('category_id', form.value.category_id.toString())
  formData.append('name', form.value.name)
  formData.append('sub_name', form.value.sub_name)
  formData.append('status', form.value.status.toString())
  formData.append('sort', form.value.sort.toString())
  formData.append('show_position', form.value.show_position.toString())
  formData.append('price', form.value.price.toString())
  formData.append('reason', form.value.reason)

  // 处理商品主图
  if (
    (isEdit.value || isView.value) &&
    typeof form.value.main_img === 'string' &&
    form.value.main_img.startsWith('/api/')
  ) {
    // 编辑或查看模式且是原有URL，去掉/api/前缀
    formData.append('main_img', form.value.main_img.replace('/api/', ''))
  } else if (
    (isEdit.value || isView.value) &&
    typeof form.value.main_img === 'string' &&
    !form.value.main_img.startsWith('/api/')
  ) {
    // 编辑或查看模式且是原有URL（没有/api/前缀）
    formData.append('main_img', form.value.main_img)
  } else {
    // 新增模式或新上传的文件
    formData.append('main_img', form.value.main_img)
  }

  // 处理商品服务图片
  if (
    (isEdit.value || isView.value) &&
    typeof form.value.goods_service === 'string' &&
    form.value.goods_service.startsWith('/api/')
  ) {
    // 编辑或查看模式且是原有URL，去掉/api/前缀
    formData.append('goods_service', form.value.goods_service.replace('/api/', ''))
  } else if (
    (isEdit.value || isView.value) &&
    typeof form.value.goods_service === 'string' &&
    !form.value.goods_service.startsWith('/api/')
  ) {
    // 编辑或查看模式且是原有URL（没有/api/前缀）
    formData.append('goods_service', form.value.goods_service)
  } else {
    // 新增模式或新上传的文件
    formData.append('goods_service', form.value.goods_service)
  }

  // 处理商品详情图片
  form.value.goods_info.forEach((item) => {
    if ((isEdit.value || isView.value) && typeof item === 'string' && item.startsWith('/api/')) {
      // 编辑或查看模式且是原有URL，去掉/api/前缀
      formData.append('goods_info[]', item.replace('/api/', ''))
    } else if (
      (isEdit.value || isView.value) &&
      typeof item === 'string' &&
      !item.startsWith('/api/')
    ) {
      // 编辑或查看模式且是原有URL（没有/api/前缀）
      formData.append('goods_info[]', item)
    } else {
      // 新增模式或新上传的文件
      formData.append('goods_info[]', item)
    }
  })

  // 处理商品图片
  form.value.goods_img.forEach((item) => {
    if ((isEdit.value || isView.value) && typeof item === 'string' && item.startsWith('/api/')) {
      // 编辑或查看模式且是原有URL，去掉/api/前缀
      formData.append('goods_img[]', item.replace('/api/', ''))
    } else if (
      (isEdit.value || isView.value) &&
      typeof item === 'string' &&
      !item.startsWith('/api/')
    ) {
      // 编辑或查看模式且是原有URL（没有/api/前缀）
      formData.append('goods_img[]', item)
    } else {
      // 新增模式或新上传的文件
      formData.append('goods_img[]', item)
    }
  })

  if (isAdd.value) {
    const res = await addGoods(formData)
    if (res.code === 200) {
      ElMessage.success('操作成功')
      router.push({
        name: 'products',
      })
    } else {
      ElMessage.error('操作失败')
    }
  } else if (isEdit.value || isView.value) {
    formData.append('id', form.value.id)
    const res = await editGoods(formData)

    if (res.code === 200) {
      ElMessage.success('操作成功')
      router.push({
        name: 'products',
      })
    } else {
      ElMessage.error('操作失败')
    }
  }
  return
}

// 辅助函数：获取分类名称
const getCategoryName = (categoryId: number) => {
  const categoryMap = {
    1: '商品分类1',
    2: '商品分类2',
    3: '商品分类3',
  }
  return categoryMap[categoryId] || `分类${categoryId}`
}

// 辅助函数：获取展示区域名称
const getShowPositionName = (position: number) => {
  const positionMap = {
    1: '家电清洗',
    2: '家电维修',
    3: '团购季',
  }
  return positionMap[position] || `区域${position}`
}
</script>
<template>
  <div class="goods-form-page-noshadow">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ name: 'products' }">商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>
        {{ isAdd ? '新增商品' : isEdit ? '编辑商品' : '商品详情' }}
      </el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :model="form" label-width="100px" class="goods-form" ref="formRef" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="商品编号" prop="code">
            <el-input v-model="form.code" placeholder="请输入" v-if="!isView" />
            <span v-else>{{ form.code }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品分类" prop="category_id">
            <el-select v-model="form.category_id" placeholder="请选择" v-if="!isView">
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="item in goodsCategoryList"
                :key="item.id"
              />
            </el-select>
            <span v-else>{{ form.category_name }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入" v-if="!isView" />
            <span v-else>{{ form.name }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="16">
          <el-form-item label="商品副标题" prop="sub_name">
            <el-input v-model="form.sub_name" placeholder="请输入" v-if="!isView" />
            <span v-else>{{ form.sub_name }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="商品状态" prop="status">
            <el-radio-group v-model="form.status" v-if="!isView">
              <el-radio :value="1">上架</el-radio>
              <el-radio :value="2">下架</el-radio>
            </el-radio-group>
            <span v-else>{{ form.status == 1 ? '上架' : '下架' }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8" v-if="isView">
          <el-form-item label="创建时间" prop="sort">
            {{ formatTime(form.created_at) }}
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8" v-if="!isView">
          <el-form-item label="商品权重" prop="sort">
            <el-input v-model="form.sort" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="!isView">
          <el-form-item label="展示区域" prop="show_position">
            <el-select v-model="form.show_position" placeholder="请选择" :disabled="isView">
              <el-option label="家电清洗" :value="1" />
              <el-option label="家电维修" :value="2" />
              <el-option label="团购季" :value="3" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="!isView">
          <el-form-item label="商品价格" prop="price">
            <el-input v-model="form.price" placeholder="请输入价格" :disabled="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="商品主图" prop="main_img">
            <template v-if="isView">
              <img
                :src="`/api/${form.main_img}`"
                alt=""
                style="width: 100px; cursor: pointer"
                @click="handleImagePreview(form.main_img)"
                class="preview-image"
              />
            </template>
            <template v-else>
              <el-upload
                ref="mainImgUploadRef"
                list-type="picture-card"
                :limit="1"
                :auto-upload="false"
                :disabled="isView"
                accept="image/*"
                :file-list="mainImgFileList"
                @change="handleMainImgChange"
                @remove="handleMainImgRemove"
                @preview="handleUploadPreview"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品图片" prop="goods_img">
            <template v-if="isView">
              <img
                alt=""
                v-for="item in form.goods_img"
                :key="item"
                style="width: 100px; margin-right: 15px; margin-bottom: 10px; cursor: pointer"
                :src="`/api/${item}`"
                @click="handleImagePreview(item)"
                class="preview-image"
              />
            </template>
            <template v-else>
              <el-upload
                ref="goodsImgUploadRef"
                list-type="picture-card"
                :limit="5"
                :auto-upload="false"
                :disabled="isView"
                accept="image/*"
                :file-list="goodsImgFileList"
                @change="handleGoodsImgChange"
                @remove="handleGoodsImgRemove"
                @preview="handleUploadPreview"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <div class="tips" style="margin-top: 60px">
            注意：商品图片会根据上传图片的顺序依次展示。
            <br />上传图片不得大于2MB
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="商品详情" prop="goods_info">
            <template v-if="isView">
              <img
                alt=""
                v-for="item in form.goods_info"
                :key="item"
                :src="`/api/${item}`"
                style="width: 100px; margin-right: 15px; margin-bottom: 10px; cursor: pointer"
                @click="handleImagePreview(item)"
                class="preview-image"
              />
            </template>
            <template v-else>
              <el-upload
                ref="goodsInfoUploadRef"
                list-type="picture-card"
                :limit="5"
                :auto-upload="false"
                :disabled="isView"
                accept="image/*"
                :file-list="goodsInfoFileList"
                @change="handleGoodsInfoChange"
                @remove="handleGoodsInfoRemove"
                @preview="handleUploadPreview"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </template>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="商品服务" prop="goods_service">
            <template v-if="isView">
              <img
                :src="`/api/${form.goods_service}`"
                alt=""
                style="width: 100px; cursor: pointer"
                @click="handleImagePreview(form.goods_service)"
                class="preview-image"
              />
            </template>
            <template v-else>
              <el-upload
                ref="goodsServiceUploadRef"
                list-type="picture-card"
                :limit="1"
                :auto-upload="false"
                :disabled="isView"
                accept="image/*"
                :file-list="goodsServiceFileList"
                @change="handleGoodsServiceChange"
                @remove="handleGoodsServiceRemove"
                @preview="handleUploadPreview"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </template>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="isEdit">
        <el-col :span="8">
          <el-form-item label="更新说明" prop="reason">
            <el-input
              v-model="form.reason"
              type="textarea"
              :rows="3"
              placeholder="请输入更新说明"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="isView">
        <el-col :span="8">
          <el-form-item label="更新说明" prop="reason">
            <span>{{ form.reason || '-' }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <div class="action-btn">
          <el-button type="primary" @click="onSubmit" v-if="!isView">提交</el-button>
          <el-button @click="router.back">关闭</el-button>
        </div>
      </el-form-item>
    </el-form>
    <!-- <div class="action-btn">
      <el-button @click="router.back" v-if="isView">取消</el-button>
    </div> -->

    <!-- 图片预览弹窗 -->
    <el-dialog
      v-model="imagePreviewVisible"
      title="图片预览"
      width="80%"
      :before-close="closeImagePreview"
      center
    >
      <div class="image-preview-container">
        <img
          :src="imagePreviewUrl"
          alt="预览图片"
          class="preview-full-image"
          @error="closeImagePreview"
        />
      </div>
    </el-dialog>
  </div>
</template>
<style scoped>
.goods-form-page-noshadow {
  margin: 0 auto;
  background: #fff;
  border-radius: 8px;
  padding: 32px 24px;
}

.goods-form {
  margin-top: 24px;
}

/* 设置表单项宽度为180px */
.goods-form :deep(.el-form-item__content) {
  width: 180px;
}

/* 对于需要全宽度的表单项（如商品图片、商品详情） */
.goods-form :deep(.el-col-24 .el-form-item__content) {
  width: 100% !important;
  max-width: none !important;
}

/* 上传组件样式 */
.goods-form :deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

.goods-form :deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

/* 恢复表单项的上下间距 */
.goods-form :deep(.el-form-item) {
  margin-bottom: 22px;
}

/* 行间距 */
.goods-form :deep(.el-row) {
  margin-bottom: 10px;
}

/* 最后一行的表单项不需要底部间距 */
.goods-form :deep(.el-row:last-child .el-form-item) {
  margin-bottom: 0;
}

.goods-img {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  background: #f2f2f2;
}

/* 面包屑样式 */
.el-breadcrumb {
  margin-bottom: 20px;
}

/* 按钮组样式 */
.goods-form :deep(.el-form-item:last-child) {
  margin-bottom: 0;
  text-align: center;
  margin-top: 30px;
}

.goods-form :deep(.el-form-item:last-child .el-button) {
  margin: 0 10px;
}

/* 商品图片上传区域样式 */
.goods-images-upload {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.goods-image-item {
  position: relative;
  width: 100px;
  height: 100px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  overflow: hidden;
}

.goods-image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.goods-image-remove {
  position: absolute;
  top: 5px;
  right: 5px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.goods-image-remove:hover {
  background: rgba(255, 0, 0, 0.7);
}

/* 查看模式样式 */
.image-preview {
  display: flex;
  align-items: center;
}

.goods-images-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.goods-image-preview-item {
  width: 80px;
  height: 80px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.goods-image-preview-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  color: #909399;
  font-style: italic;
}

.goods-info-content {
  max-height: 200px;
  overflow-y: auto;
  white-space: pre-wrap;
  line-height: 1.6;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.action-btn {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  width: 100%;
}

/* 图片预览相关样式 */
.preview-image {
  transition: transform 0.2s ease-in-out;
  border-radius: 4px;
}

.preview-image:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.image-preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background: #f5f5f5;
  border-radius: 8px;
  overflow: hidden;
}

.preview-full-image {
  max-width: 100%;
  max-height: 80vh;
  object-fit: contain;
  border-radius: 4px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

/* 图片预览弹窗样式优化 */
:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #e4e7ed;
  padding: 20px 20px 10px;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  color: #303133;
}
</style>
